/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
/*
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        if(root==nullptr){
            return res;
        }
        hou(res, root);
        return res;
    }
    void hou(vector<int>& res, TreeNode* root){
        if(root==nullptr){
            return;
        }
        hou(res, root->left);
        hou(res, root->right);
        res.push_back(root->val);
    }
    
*/
    vector<int> postorderTraversal(TreeNode* root) {
        vector<int> res;
        stack<TreeNode*> s;
        TreeNode* cur = root;
        TreeNode* prev = nullptr;
        while(cur || !s.empty()){
            while(cur){
                s.push(cur);
                cur=cur->left;
            }
            cur=s.top();
            if(cur->right!=nullptr && cur->right != prev){
                cur=cur->right;
            }else{
                res.push_back(cur->val);
                prev=s.top();
                s.pop();
                cur=nullptr;
            }
        }
        return res;
    }
};
